package com.lw.leetcode.linked.a;

import com.lw.leetcode.linked.ListNode;

/**
 * 剑指 Offer 25. 合并两个排序的链表
 * 21. 合并两个有序链表
 *
 * @Author liw
 * @Date 2021/9/5 14:33
 * @Version 1.0
 */
public class MergeTwoLists {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {


        ListNode sum = null;
        ListNode sum2 = null;
        if (l1 == null && l2 == null) {
            return null;
        }
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        int a = l1.val;
        int b = l2.val;

        if (a > b) {
            sum = l2;
            sum2 = l2;
            l2 = l2.next;
        } else {
            sum = l1;
            sum2 = l1;
            l1 = l1.next;
        }
        while (true) {
            if (l1 == null) {
                sum.next = l2;
                return sum2;
            }
            if (l2 == null) {
                sum.next = l1;
                return sum2;
            }
            a = l1.val;
            b = l2.val;

            if (a > b) {
                sum.next = l2;
                l2 = l2.next;
            } else {
                sum.next = l1;
                l1 = l1.next;
            }
            sum = sum.next;
        }
    }
}
